#include <iostream>
#include <unistd.h>
#include <pthread.h>

//打印子线程id
//不可重入函数被重入
//一个子线程崩溃导致子线程崩溃

std::string ToHex(pthread_t pid)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), "0x%lx", pid);
    return buffer;
}
void *rutine1(void *args)
{
    std::string name = static_cast<const char *>(args);
    while (true)
    {
        std::cout << "我是子线程:" << name << "Pid:" << ToHex(pthread_self()) << std::endl;
        sleep(2);
    }
    return nullptr;
}
void *rutine2(void *args)
{
    sleep(5);
    std::string name = static_cast<const char *>(args);
    std::cout << "我是子线程:" << name << "Pid:" << ToHex(pthread_self()) << std::endl;
    //子线程崩溃会导致整个进程崩溃,因为操作系统是向进程发送信号终止的
    std::cout<<"我将在10秒后访问空指针导致崩溃"<<std::endl;
    sleep(10);
    char* p=nullptr;
    *p='a';
    return nullptr;
}

int main()
{
    // 创建多个子线程
    pthread_t pth1, pth2, pth3;
    //1和2子线程都同时访问rutine1函数
    //而显示器文件就相当于被线程共享的公共资源
    //同时访问并修改不加保护的公共资源会出现问题,乱序输出
    pthread_create(&pth1, nullptr, rutine1, (void *)"pthread-1");
    pthread_create(&pth1, nullptr, rutine1, (void *)"pthread-2");
    //所有子线程共享进程的时间片

    pthread_create(&pth1, nullptr, rutine2, (void *)"pthread-3");
    while(true)
    {
        std::cout<<"我是main线程,Pid"<<ToHex(pthread_self())<<std::endl;
        sleep(2);
    }
    return 0;
}